import Taro from '@tarojs/taro'
import map from '@/utils/map'
import { STORECODE, UPDATA_CITY, CITYLIST, UPDATA_STORELOCATION, UPDATA_LOCATION, STORE_LOCATION, CITYGROUP, SET_CUSTOM_ADDRESS, IS_OPENLOCATION,UPDATA_CITYLOCATION,UPDATA_LONGITUDE_LATITUDE } from './action-types'

// 位置
export const initLocation = address => {
    return async dispatch => {
        dispatch({
            type: UPDATA_LOCATION,
            address
        })
				console.log('initLocation----address',address)
        return address
    }
}

// 更新门店首页
export const updateStore = (store) => {
    return dispatch => {
        let newStore: any = null
        let storeCode = ''
        if (store) {
            newStore = {
                ...store,
                timestamp: +new Date()
            }
        }
        Taro.setStorageSync(STORE_LOCATION, newStore)
        if (newStore) {
            storeCode = newStore.storeCode
        }
        Taro.setStorageSync(STORECODE, storeCode)
        dispatch({
            type: UPDATA_STORELOCATION,
            storeLocation: newStore
        })
        return newStore
    }
}

// 更新城市首页
export const updateCity = (city) => {
  console.log('执行了吗-------updateCity')
	return dispatch => {
			let newCity: any = null
			if (city) {
				newCity = {
					...city,
					timestamp: +new Date()
				}
			}
			Taro.setStorageSync('CURRENT_LOCATION_INFO', newCity)
			dispatch({
					type: UPDATA_CITYLOCATION,
					cityLocation: newCity
			})
			return newCity
	}
}

// 记录当前位置经纬度
export const updateCurrentLocation = (city) => {
	return dispatch => {
			let newCity: any = null
			if (city) {
				newCity = {
					...city,
				}
			}
			Taro.setStorageSync('CURRENT_LONGITUDE_LATITUDE', newCity)
			dispatch({
					type: UPDATA_LONGITUDE_LATITUDE,
					currentlongitudeLatitude: newCity
			})
			return newCity
	}
}

// 城市列表
export const getCityList = () => {
    return async dispatch => {
        const cityGroup = Taro.getStorageSync(CITYGROUP)
        let cityList:any = []
        if (cityGroup) {
            cityList = cityGroup
        } else {
            cityList = await map.getCityList()
            Taro.setStorageSync(CITYGROUP, cityList)
        }
        dispatch({
            type: CITYLIST,
            cityList
        })
        return cityList
    }
}

// 手动切换城市
export const switchCity = (cityName) => {
    return dispatch => {
        dispatch({
          type: UPDATA_CITY,
          cityName
        })
    }
}

// 设置定位开启状态
export const setOpenLocation = status => {
    return dispatch => {
        dispatch({
            type: IS_OPENLOCATION,
            isOpenLocation: status
        })
    }
}

// 手动定位状态（是： 有地址信息的值, 否：false）
export const customStatus = status => {
    return dispatch => {
        Taro.setStorageSync('CUSTOMA_DDRESS', status)
        dispatch({
            type: SET_CUSTOM_ADDRESS,
            customAddress: status
        })
    }
}
